package com.bootcamp.servlet.util;

import com.bootcamp.servlet.bean.UserInfo;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * @program: wrok-1101
 * @description:
 * @author: Keyu Li
 * @create: 2021-11-01 21:46
 **/

public class UserInfoBeanHandler {
    private UserInfoBeanHandler() {
    }

    public static UserInfo transferMapToBean(Map<String, String[]> parameters) {
        Class<?> userClass = null;
        try {
            //获取 class 对象
            userClass = Class.forName("com.bootcamp.servlet.bean.UserInfo");
            // 创建对象
            UserInfo userInfo = (UserInfo) userClass.newInstance();
            // 获取所有成员变量名
            Field[] declaredFields = userClass.getDeclaredFields();
            for (Field field : declaredFields) {
                // 得到变量名
                String name = field.getName();
                // 得到 set方法
                String methodName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1);
                Method method = userClass.getMethod(methodName, field.getType());
                // invoke set 方法
                String[] values = parameters.get(name);
                String simpleName = field.getType().getSimpleName();
                if (values == null || values.length == 0) continue;
                if ("String".equals(simpleName)) {
                    // 以数组方式传入可变参数
                    method.invoke(userInfo, values);
                } else if ("Integer".equals(simpleName)) {
                    method.invoke(userInfo, Integer.parseInt(values[0]));
                } else if ("String[]".equals(simpleName)) {
                    method.invoke(userInfo, (Object) values);
                } else {
//                    throw new IllegalArgumentException("value type not correspond!");
                    continue;
                }
            }
            return userInfo;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        return null;
    }
}
